<?php
error_reporting(5);
// 在新媒体管理界面添加一个的选项
add_filter('media_upload_tabs', 'wp_storage_to_ttk_media_tab' );
function wp_storage_to_ttk_media_tab($tabs){
	if(!is_wp_to_ttk_active())return;
	$newtab = array('file_from_ttk' => '贴图库');
    return array_merge($tabs,$newtab);
}
// 这个地方需要增加一个中间介wp_iframe，这样就可以使用wordpress的脚本和样式
add_action('media_upload_file_from_ttk','media_upload_file_from_ttk_iframe');
function media_upload_file_from_ttk_iframe(){
	wp_iframe('wp_storage_to_ttk_media_tab_box');
	//wp_iframe('wp_storage_to_ttk_media_tab_box');
}
// 去除媒体界面的多余脚本
add_action('admin_init','wp_storage_to_ttk_media_iframe_remove_actions');
function wp_storage_to_ttk_media_iframe_remove_actions(){
	global $wp_version,$hook_suffix;
	if(!$hook_suffix!='media-upload.php'){
		return  ;
	}
	if(!isset($_GET['tab']) || $_GET['tab'] != 'file_from_ttk'){
		return;
	}
	wp_enqueue_script( 'mjquery', plugins_url("jquery.js",__FILE__ ),array('jquery'));
	//wp_enqueue_script( 'mjquery',home_url().'/wp-includes/js/jquery/jquery.js' );
	wp_enqueue_script( 'uploadify', plugins_url("uploadify.js",__FILE__ ),array('jquery'));
	
	remove_all_actions('admin_head');
	remove_all_actions('in_admin_header');
}
// 在上面产生的显示出网盘内的文件

function wp_storage_to_ttk_media_tab_box() {
$options = get_option('wptottk_options'); 
$accesskey = $options['accesskey'];
$secretkey = $options['secretkey'];
$album = $options['xiangceid'];
$fanhui = $options['fanhuileixin'];
$wailian = $options['quwailian'];
if(empty($wailian)){
	$wailian==1;
}
if(empty($fanhui)){
	$fanhui==1;
}
?>
<style>
.upload_c_a{width:100%;height:40px;line-height:40px;margin:10px 0px;position:relative}.upload_c_b{width:100%}.upload_c_c{font-size:12px}.upload-queuebody{height:300px;padding:0;margin:0;border:1px solid #ccc;margin-bottom:15px}.upload-queuehead{width:100%;height:30px;padding:0;margin:0;background-color:#efefef}#file_upload{position:relative;margin:0;margin-left:10px;float:left}.upload-button{line-height:30px;overflow:hidden;text-align:center;background-color:#090;background-position:center top;background-repeat:no-repeat;border:2px solid #090;color:#FFF;font:bold 12px Arial,Helvetica,sans-serif;text-align:center}.upload-queue{height:260px;padding:0;margin:0;overflow-x:auto}.cbtn1{float:right;width:104px;border:0;padding:0;background-color:#090;color:#fff;font-size:14px;font-weight:bold;cursor:pointer;height:38px}.upload-queue-item{background-color:#f5f5f5;border-bottom:1px dotted #d5d5d5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;font:12px Arial,Helvetica,Sans-serif;margin-top:3px;padding:15px;width:45%;float:left;margin-left:5px}.upload-queue-item .close{background:url('<?php echo plugins_url("uploadifive-cancel.png",__FILE__ ); ?>') 0 0 no-repeat;display:block;float:right;height:16px;text-indent:-9999px;width:16px}.upload-queue-item .progress{border:1px solid #d0d0d0;height:3px;margin-top:5px;width:100%}.upload-queue-item .progress-bar{background-color:#0072bc;height:3px;width:0}
html,body{background-color:#fff;background-attachment:fixed;}
#opt-on-pcs-tabs{padding:0 1em 0 1em;border-bottom:1px solid #dedede;margin-bottom:1em;font-size:1.1em;
	width:100%;
	position:fixed;
	_position:absolute;
	left:0;
	top:0;
	_top:expression(documentElement.scrollTop);
	background:#fff;
}
#opt-on-pcs-tabs .right{margin-right:3em;}
#files-on-pcs{margin:10px;padding-top:90px;}
.file-on-pcs{width:120px;height:120px;overflow:hidden;float:left;margin:5px;padding:2px;}
.file-thumbnail{width:120px;height:96px;overflow:hidden;background-color:#ccc;}
.file-type-dir .file-thumbnail{background-color:#FDCE5F;}
.file-type-video .file-thumbnail{background-color:#000000;}
.file-type-audio .file-thumbnail{background-color:#8A285C;}
.file-thumbnail img{max-width:100%;height:auto;}
.file-name{line-height:1em;margin-top:3px;}
.selected{background-color:#008000;color:#fff;}
.selected-file{background-color:#A30000;color:#fff;}
.selected-video{background-color:#2E2EFF;color:#fff;}
.selected-audio{background-color:#FF00FF;color:#000000;}
.opt-area{margin:0 10px;padding-bottom:20px;}
.alert{color:#D44B25;margin:0 10px;padding-bottom:20px;}
.hidden{display:none;}
#upload-to-pcs{text-align:center;padding-top:150px;}
.page-navi{font-size:14px;text-align:center;background-color:#E62114;}
.page-navi a{color:#fff;text-decoration:none;}
#prev-page a{padding:5px;display:block;}
#prev-page a:hover{background-color:#1BA933;}
#next-page a{padding:5px;display:block;}
#next-page a:hover{background-color:#1BA933;}
#rename-file{width:118px;height:16px;line-height:16px;border:0;background:#fff;padding:0;}
</style>
<script type="text/javascript">
var wailian='<?php echo $wailian; ?>';
var fanhui='<?php echo $fanhui; ?>';
jQuery(function($) {
    var html='';
    $('#file_upload').uploadify({
        'swf': '<?php echo plugins_url("uploadify.swf",__FILE__ ); ?>',
        'uploader': 'http://api.tietuku.com/v1/Up',
        'auto': false,
        'fileObjName': 'file',
        'fileSizeLimit': '10MB',
        'fileTypeExts': '*.jpg;*.gif;*.jpeg;*.png;',
        'fileTypeDesc': 'Any old file you want...',
        'method': 'POST',
        'multi': true,
        'queueID': 'upload-queue',
        'buttonText': '选择图片',
        'buttonClass': 'upload-button',
        'width': '104',
        'height': '34',
        'queueSizeLimit': 300,
        'formData': {
            'Token': '',
        },
        'removeCompleted': false,
        'itemTemplate': '<div class="upload-queue-item" id="${fileID}"><a href="javascript:$(\'#file_upload\').uploadify(\'cancel\',\'${fileID}\')" class="close">X</a><div><span class="fileName">${fileName}</span><span class="fileinfo"></span></div><div class="progress"><div class="progress-bar"></div></div></div>',
        'onUploadProgress': function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            nowper = (bytesUploaded * 100) / bytesTotal;
            nowper = parseInt(nowper);
            $('#' + file.id).find('.fileName').html( file.name +'&nbsp;&nbsp;&nbsp;正在上传...');
            $("#" + file.id + " .progress .progress-bar").css("width", String(nowper) + "%");
        },'onUploadStart': function(file) {
            $('#uploadbtn').val('正在上传');
            $('#uploadbtn').attr("disabled", "disabled");
        },
        'onUploadSuccess': function(file, data, response) {
           $('#' + file.id).find('.fileName').html('<font color="blue">' + file.name +'&nbsp;&nbsp;&nbsp;上传成功</font>');
            var obj=eval('(' + data + ')');
            var arr=obj.url.split('.'+obj.type);
            if(fanhui==2){
            	obj.url=arr[0]+'t.jpg'+arr[1];
            }else if(fanhui!=3&&obj.type!='gif'){
            	obj.url=arr[0]+'s.'+obj.type+arr[1];
            }
            if(wailian=='2'){
            	var arr=obj.url.split('>');
            	obj.url=arr['1']+'>';
            }
         	html+=obj.url;
        },
        'onQueueComplete': function(queueData) {
            $('#uploadbtn').val('上传图片');
            $('#uploadbtn').removeAttr("disabled");
            $('#insert-btnh').removeAttr('disabled')
         },
       'onUploadError': function(file, errorCode, errorMsg, errorString) {
            $('#' + file.id).find('.fileName').html('<font color="red">' + file.name +'&nbsp;&nbsp;&nbsp;上传失败</font>');
            $('#uploadbtn').val('上传图片');
            $('#uploadbtn').removeAttr("disabled")
        },
    });
$('#uploadbtn').click(function(){
		if($("#file_upload").data('uploadify').queueData.queueLength>0){
			
				
				var data= {
			ak:"<?php echo $accesskey ;?>",
			sk: "<?php echo $secretkey ;?>",
			xcid: "<?php echo $album ;?>",
            action: "up",
			html: "htmlurl"
        };
       var url="<?php echo plugins_url("token.php",__FILE__ ); ?>?callback=?";
       
            $.getJSON(url,data,function(response){
			var token = response.Token;
				$('#file_upload').uploadify('settings','formData',{'Token':token});
				$('#file_upload').uploadify('upload','*');
			 })
			 
				}
		return false;
	});
    $('#insert-btnh').click(function(){
        $('#file_upload').uploadify('cancel', '*');
        window.parent.send_to_editor(html);
        html='';
        $('#upload-queue').empty();
        $(this).attr("disabled", "disabled");
        window.parent.tb_remove();
    });
});
</script>
<script type="text/javascript">
var paged = 1;
function pagenew()
　　{
	var data= {
			ak:"<?php echo $accesskey ;?>",
			sk: "<?php echo $secretkey ;?>",
			xcid: "<?php echo $album ;?>",
            action: "xc",
			page: paged
        };
       var url="<?php echo plugins_url("token.php",__FILE__ ); ?>?callback=?";
        $(function(){
            $.getJSON(url,data,function(response){
			var token = response.Token;
		$.ajax({
			url:'http://api.tietuku.com/v1/List',
			type:'POST',
			dataType:'json',
			data:{'Token': token },
			success:function(data){
				var myobj=eval(data);  
for(var i=0;i<myobj.length;i++){  
	myobj[i].linkurl1=myobj[i].linkurl;
	var arr=myobj[i].linkurl.split('.');
	myobj[i].linkurl=arr[0]+'.'+arr[1]+'.'+arr[2]+'t.jpg';
  getList =  '<div class="file-on-pcs file-type-file can-select " data-file-name="' + myobj[i].name + '" data-file-type="image" data-file-src="' + myobj[i].linkurl1 + '" data-file-link="'+myobj[i].showurl+'" data-file-ext="'+myobj[i].ext+'"><div class="file-thumbnail"><img src="' + myobj[i].linkurl + '" /></div><div class="file-name" title="点击名称可以修改本次插入的附件名">' + myobj[i].name + '</div></div>';
 
   $('#files-on-ttk').append(getList);
}  
			}
		});
            })
        }); 
 }

jQuery(function($){
	// 选择要插入的附件
	$('#files-on-ttk div.can-select').live('click',function(e){
		var _t = $(this),
			file_type = _t.attr('data-file-type');
		if($('#rename-file').is(":visible"))return;
		_t.toggleClass('selected');
	
	});
	// 调整图片信息
	$('.selected .file-name').live('click',function(){
		var _t = $(this),
			text = _t.text();
		if($('#rename-file').is(":visible"))text = $('#rename-file').val();
		_t.html('<input type="text" value="'+text+'" id="rename-file" />');
		$('#rename-file').focus();
	});
	$('#rename-file').live('focusout',function(){
		var _t = $('#rename-file'),
			fileName = _t.parent(),
			text = _t.val();
		if(text==''){
			text = fileName.parent().attr('data-file-name');
		}else{
			fileName.parent().attr('data-file-name',text);
		}
		fileName.text(text);
	}).live('keypress',function(e){
		var e = document.all ? window.event : e;
		if(e.keyCode == "13"){
			$(this).trigger('focusout');
		}
	});
	// 点击插入按钮
$('#insert-btn').click(function(){
		if($('div.selected').length > 0){
				var html='';
			$('div.selected').each(function(){
				var _t = $(this),
					file_name = _t.attr('data-file-name'),
					file_path = _t.attr('data-file-path'),
					file_type = _t.attr('data-file-type'),
					file_src = _t.attr('data-file-src'),
					file_link = _t.attr('data-file-link'),
					file_ext = _t.attr('data-file-ext');
					var arr=file_src.split('.'+file_ext);
					if(fanhui==2){
		            	file_src=arr[0]+'t.jpg'+arr[1];
		            }else if(fanhui!=3&&file_ext!='gif'){
		            	file_src=arr[0]+'s.'+file_ext+arr[1];
		            }
					var tmp='<img src="'+file_src+'" class="image" alt="'+file_name+'" />';
		            if(wailian!='2'){
		            	tmp='<a href="'+file_link+'" target="_blank">'+tmp+'</a>';
		            }
					html+=tmp;
			});
			window.parent.send_to_editor(html);
			window.parent.tb_remove();
		}else{
			alert('没有选择任何图片');
		}
	});
	// 点击关闭按钮
	$('#close-btn').click(function(){
		window.parent.tb_remove();
	});
	// 清除选择的图片
	$('#clear-btn').click(function(){
		$('.selected').removeClass('selected');
		$('.selected-video').removeClass('selected-video');
		$('.selected-audio').removeClass('selected-audio');
		$('.selected-file').removeClass('selected-file');
	});

	// 点击切换到上传面板
	$('#show-upload-area').toggle(function(e){
		e.preventDefault();
		$('#files-on-ttk,#next-page,#prev-page,#opt-area').hide();
		$('#upload-to-ttk').show();
		$(this).text('返回列表');
	},function(e){
		e.preventDefault();
		$('#upload-to-ttk').hide();
		$('#files-on-ttk,#next-page,#prev-page,#opt-area').show();
		$(this).text('上传到这里');
	});
	// 点击下一页
	$('#next-page a').live('click',function(e){
	e.preventDefault();
	paged= paged + 1;
	var html="";
					var _t = $(this),
			href = _t.attr('href'),
			loading = _t.attr('data-loading');
	var data= {
			ak:"<?php echo $accesskey ;?>",
			sk: "<?php echo $secretkey ;?>",
			xcid: "<?php echo $album ;?>",
            action: "xc",
			page: paged
        };
       var url="<?php echo plugins_url("token.php",__FILE__ ); ?>?callback=?";
        
            $.getJSON(url,data,function(response){
			//alert(response.Token);
			var token = response.Token;
		$.ajax({
			url:'http://api.tietuku.com/v1/List',
			type:'POST',
			dataType:'json',
			data:{'Token':token },
			beforeSend:function(){
				_t.text('正在加载...');
				_t.attr('data-loading','true');
			},
			success:function(data){
				var myobj=eval(data);  
for(var i=0;i<myobj.length;i++){  
	myobj[i].linkurl1=myobj[i].linkurl;
	var arr=myobj[i].linkurl.split('.');
	myobj[i].linkurl=arr[0]+'.'+arr[1]+'.'+arr[2]+'t.jpg';
  getList =  '<div class="file-on-pcs file-type-file can-select " data-file-name="' + myobj[i].name + '" data-file-type="image" data-file-src="' + myobj[i].linkurl1 + '" data-file-link="'+myobj[i].showurl+'" data-file-ext="'+myobj[i].ext+'"><div class="file-thumbnail"><img src="' + myobj[i].linkurl + '" /></div><div class="file-name" title="点击名称可以修改本次插入的附件名">' + myobj[i].name + '</div></div>';
  html +=getList
}  
document.getElementById("files-on-ttk").innerHTML = html

					nextPageLink = "12";

				if(nextPageLink != undefined){
					_t.attr('href',nextPageLink);
					_t.text('下一页');
					_t.attr('data-loading','false');
				}else{
					$('#next-page').hide().remove();
				}
			}
		});
			

            })
      
});
	// 点击上一页
	$('#prev-page a').live('click',function(e){
	e.preventDefault();
	paged= paged - 1;
	var html="";
					var _t = $(this),
			href = _t.attr('href'),
			loading = _t.attr('data-loading');
	var data= {
			ak:"<?php echo $accesskey ;?>",
			sk: "<?php echo $secretkey ;?>",
			xcid: "<?php echo $album ;?>",
            action: "xc",
			page: paged
        };
       var url="<?php echo plugins_url("token.php",__FILE__ ); ?>?callback=?";
        
            $.getJSON(url,data,function(response){
			//alert(response.Token);
			token = response.Token;
		
		$.ajax({
			url:'http://api.tietuku.com/v1/List',
			type:'POST',
			dataType:'json',
			data:{'Token': token },
			beforeSend:function(){
				_t.text('正在加载...');
				_t.attr('data-loading','true');
			},
			success:function(data){
				var myobj=eval(data);  
for(var i=0;i<myobj.length;i++){  
	myobj[i].linkurl1=myobj[i].linkurl;
	var arr=myobj[i].linkurl.split('.');
	myobj[i].linkurl=arr[0]+'.'+arr[1]+'.'+arr[2]+'t.jpg';
  getList =  '<div class="file-on-pcs file-type-file can-select " data-file-name="' + myobj[i].name + '" data-file-type="image" data-file-src="' + myobj[i].linkurl1 + '" data-file-link="'+myobj[i].showurl+'" data-file-ext="'+myobj[i].ext+'"><div class="file-thumbnail"><img src="' + myobj[i].linkurl + '" /></div><div class="file-name" title="点击名称可以修改本次插入的附件名">' + myobj[i].name + '</div></div>';
  html +=getList
}  
document.getElementById("files-on-ttk").innerHTML = html

					nextPageLink = "12";

				if(nextPageLink != undefined){
					_t.attr('href',nextPageLink);
					_t.text('下一页');
					_t.attr('data-loading','false');
				}else{
					$('#next-page').hide().remove();
				}
			}
		});
			

            })
       
});
});
　window.onload = pagenew;
//"jQuery('#show-media-alert').toggle();jQuery('html,body').animate({scrollTop:jQuery('#show-media-alert').offset().top},500);"
</script>
<div id="opt-on-ttk-tabs">
	<p> <a href="#upload-to-ttk" class="button" id="show-upload-area">上传到这里</a></p>
	<p>
		<button id="insert-btn" class="button-primary">插入</button>
		<button id="clear-btn" class="button">清除</button>
		<button id="close-btn" class="button">关闭</button>
		<a href="" class="button" id="reflush">刷新</a>
		<a href="http://tietuku.com/" target="_blank" class="button">管理</a>
		<a href="javascript:void(0)" onclick="jQuery('html,body').animate({scrollTop:0},500)" class="button right">顶部</a>
	</p>
	<div class="clear"></div>
</div>
<div id="files-on-ttk">

</div>
<div style="clear:both;"></div>
<div id="upload-to-ttk" class="hidden">
	 <div class="sapload">
    <div class="upload_c_a">
        <input id="file_upload" name="file" type="file" multiple="true">
        <input type="button" id="uploadbtn" class="cbtn1" value="上传图片" />
    </div>
    <div class="upload_c_b">
        <div id="uploadcontainer">
            <div class="upload-queuebody">
                <div class="upload-queuehead"></div>
                <div class="upload-queue" id="upload-queue"></div>
            </div>
            <div styel="clear:both;"></div>
        </div>
    </div>
    <div class="upload_c_a">
        <input type="button" id="insert-btnh" class="cbtn1" style='float:left;' value="全部插入" disabled />
    </div>
    <div styel="clear:both;"></div>
    <div class="upload_c_c">温馨提示：图片格式支持JPG、JPEG、GIF、PNG、BMP；一次可添加上传300张图片，单张图片不可超过10M。</div>
</div>
</div>
<div class="opt-area" id="opt-area">
<p id="prev-page" class="page-navi"><a href="">上一页</a></p>
<p id="next-page" class="page-navi"><a href="">下一页</a><p>
</div>
<div class="alert hidden" id="show-media-alert">

</div>
<?php
}
